jun.PenjualanGrid = Ext.extend(Ext.grid.GridPanel, {
    title: "Penjualan Sales",
    id: 'docs-jun.PenjualanGrid',
    iconCls: "silk-grid",
    viewConfig: {
        forceFit: true
    },
    sm: new Ext.grid.RowSelectionModel({
        singleSelect: true
    }),
    plugins: [new Ext.ux.grid.GridHeaderFilters],
    columns: [
        {
            header: 'Ref. Dok',
            sortable: true,
            resizable: true,
            dataIndex: 'doc_ref',
            width: 100
        },
        {
            header: 'Konsumen',
            sortable: true,
            resizable: true,
            dataIndex: 'konsumen_id',
            width: 100,
            renderer: jun.renderNamaKonsumen
        },
        {
            header: 'Jatuh Tempo',
            sortable: true,
            resizable: true,
            dataIndex: 'tempo',
            width: 100
        },
        {
            header: 'Total',
            sortable: true,
            resizable: true,
            dataIndex: 'total',
            width: 100,
            align: "right",
            renderer: Ext.util.Format.numberRenderer("0,0")
        },
        {
            header: 'Uang Muka',
            sortable: true,
            resizable: true,
            dataIndex: 'uang_muka',
            width: 100,
            align: "right",
            renderer: Ext.util.Format.numberRenderer("0,0")
        },
        {
//            xtype: 'checkcolumn',
            header: 'Final?',
            sortable: true,
            resizable: true,
            dataIndex: 'final',
            width: 25,
            renderer: jun.renderSudah
        }
    ],
    initComponent: function () {
        this.store = jun.rztPenjualan;
        this.tbar = {
            xtype: 'toolbar',
            items: [
                {
                    xtype: 'buttongroup',
                    columns: 2,
                    defaults: {
                        scale: 'small'
                    },
                    items: [
                        {
                            text: 'Tanggal :'
                        },
                        {
                            xtype: 'xdatefield',
                            format: 'd M Y',
                            ref: '../../tgl',
                            id: 'tglpenjgridid'
                        },
                        {
                            text: 'Salesman :'
                        },
                        {
                            xtype: 'combo',
                            typeAhead: true,
                            triggerAction: 'all',
                            lazyRender: true,
                            mode: 'local',
                            ref: '../../sales',
                            id: 'salespenjgridid',
                            fieldLabel: 'salesman_id',
                            store: jun.rztSalesman,
                            forceSelection: true,
                            hiddenName: 'salesman_id',
                            valueField: 'salesman_id',
                            displayField: 'salesman_name',
                            allowBlank: false,
                            anchor: '100%'
                        }
                    ]},
                {
                    xtype: 'buttongroup',
                    id:'buttongroupbtnAddbtnEdit',
                    columns: 1,
                    defaults: {
                        scale: 'small'
                    },
                    items: [
                        {
                            xtype: 'button',
                            text: 'Tambah Faktur',
                            ref: '../../btnAdd'
                        },
                        {
                            xtype: 'button',
                            text: 'Edit Faktur',
                            ref: '../../btnEdit'
                        }
                    ]
                },
                {
                    xtype: 'buttongroup',
                    id:'buttongroupbtnCetak',
                    columns: 3,
                    defaults: {
                        scale: 'large'
                    },
                    items: [
                        {
                            xtype: 'button',
                            text: 'Cetak<br>Faktur',
                            height: 44,
                            ref: '../../btnCetak',
                            scale: 'large'
                        }
                    ]},
                {
                    xtype: 'buttongroup',
                    id:'buttongroupbtnDOSbtnDOF',
                    columns: 1,
                    defaults: {
                        scale: 'small'
                    },
                    items: [
                        {
                            xtype: 'button',
                            text: 'DO Sementara',
                            ref: '../../btnDOS'
                        },
                        {
                            xtype: 'button',
                            text: 'DO Final',
                            ref: '../../btnDOF'
                        }
                    ]
                },
                {
                    xtype: 'buttongroup',
                    id:'buttongroupbtnBebanSalesbtnReturBotol',
                    columns: 1,
                    defaults: {
                        scale: 'small'
                    },
                    items: [
                        {
                            xtype: 'button',
                            text: 'Biaya Sales',
                            ref: '../../btnBebanSales',
                            scale: 'small'
                        },
                        {
                            xtype: 'button',
                            text: 'Retur Botol',
                            ref: '../../btnReturBotol',
                            scale: 'small'
                        }
                    ]
                },
                {
                    xtype: 'buttongroup',
                    id:'buttongroupbtnPiutangbtnSetorKas',
                    columns: 3,
                    defaults: {
                        scale: 'large'
                    },
                    items: [
                        {
                            xtype: 'button',
                            text: 'Pelunasan<br>Piutang',
                            height: 44,
                            ref: '../../btnPiutang',
                            scale: 'large'
                        },
                        {
                            xtype: 'button',
                            text: 'Setoran<br>Kas',
                            height: 44,
                            ref: '../../btnSetorKas',
                            scale: 'large'
                        }
                    ]},
                {
                    xtype: 'buttongroup',
                    id:'buttongroupbtnKirimbtnKasMasuk',
                    columns: 3,
                    defaults: {
                        scale: 'large'
                    },
                    items: [
                        {
                            xtype: 'button',
                            text: 'Laporan<br>Pengiriman',
                            height: 44,
                            ref: '../../btnKirim',
                            scale: 'large'
                        },
                        {
                            xtype: 'button',
                            text: 'Laporan<br>Kas Masuk',
                            height: 44,
                            ref: '../../btnKasMasuk',
                            scale: 'large'
                        }
                    ]}
            ]
        };
        if (jun.rztSalesman.getTotalCount() === 0) {
            jun.rztSalesman.load();
        }
        if (jun.rztKonsumen.getTotalCount() === 0) {
            jun.rztKonsumen.load();
        }
        if (jun.rztKonsumenLib.getTotalCount() === 0) {
            jun.rztKonsumenLib.load();
        }
        if (jun.rztArea.getTotalCount() === 0) {
            jun.rztArea.load();
        }
        if (jun.rztPasar.getTotalCount() === 0) {
            jun.rztPasar.load();
        }
        if (jun.rztBarang.getTotalCount() === 0) {
            jun.rztBarang.load();
        }
        if (jun.rztBarangLib.getTotalCount() === 0) {
            jun.rztBarangLib.load();
        }
        if (jun.rztBank.getTotalCount() === 0) {
            jun.rztBank.load();
        }
        if (jun.rztJenisBotolLib.getTotalCount() === 0) {
            jun.rztJenisBotolLib.load();
        }
        if (jun.rztChartMasterNonKasBank.getTotalCount() === 0) {
            jun.rztChartMasterNonKasBank.load();
        }
        if (jun.rztChartMasterLib.getTotalCount() === 0) {
            jun.rztChartMasterLib.load();
        }
        jun.PenjualanGrid.superclass.initComponent.call(this);
        jun.rztPenjualan.removeAll();
        this.btnAdd.on('Click', this.loadForm, this);
        this.btnDOS.on('Click', this.onbtnDOSClick, this);
        this.btnSetorKas.on('Click', this.onbtnSetorKasClick, this);
        this.btnKirim.on('Click', this.onbtnKirimClick, this);
        this.btnKasMasuk.on('Click', this.onbtnKasMasuk, this);
        this.btnDOF.on('Click', this.onbtnDOFClick, this);
        this.sales.on('select', this.onSalesChange, this);
        this.tgl.on('select', this.onSalesChange, this);
        this.btnEdit.on('Click', this.loadEditForm, this);
        this.btnPiutang.on('Click', this.onbtnPiutangClick, this);
        this.btnBebanSales.on('Click', this.onbtnBebanSalesClick, this);
        this.btnReturBotol.on('Click', this.onbtnReturBotolClick, this);
        this.btnCetak.on('Click', this.onbtnCetakClick, this);
        this.getSelectionModel().on('rowselect', this.getrow, this);
        Ext.getCmp('buttongroupbtnKirimbtnKasMasuk').setVisible(SYSTEM_PENJUALAN_3);
        Ext.getCmp('buttongroupbtnPiutangbtnSetorKas').setVisible(SYSTEM_PENJUALAN_3);
        Ext.getCmp('buttongroupbtnBebanSalesbtnReturBotol').setVisible(SYSTEM_PENJUALAN_3);
        Ext.getCmp('buttongroupbtnAddbtnEdit').setVisible(SYSTEM_PENJUALAN_1);
        Ext.getCmp('buttongroupbtnCetak').setVisible(SYSTEM_PENJUALAN_1);
        Ext.getCmp('buttongroupbtnDOSbtnDOF').setVisible(SYSTEM_PENJUALAN_5);
        jun.rztBiayaSales.on({
            beforeload: {
                fn: function (a, b) {
                    b.params = {
                        sales: Ext.getCmp('salespenjgridid').getValue(),
                        tgl: Ext.getCmp('tglpenjgridid').getValue()
                    }
                },
                scope: this
            }
        });
        jun.rztDos.on({
            beforeload: {
                fn: function (a, b) {
                    b.params = {
                        sales: Ext.getCmp('salespenjgridid').getValue(),
                        tgl: Ext.getCmp('tglpenjgridid').getValue()
                    }
                },
                scope: this
            }
        }),
            jun.rztSetorKasSales.on({
                beforeload: {
                    fn: function (a, b) {
                        b.params = {
                            sales: Ext.getCmp('salespenjgridid').getValue(),
                            tgl: Ext.getCmp('tglpenjgridid').getValue()
                        }
                    },
                    scope: this
                }
            }),
            jun.rztDof.on({
                beforeload: {
                    fn: function (a, b) {
                        b.params = {
                            sales: Ext.getCmp('salespenjgridid').getValue(),
                            tgl: Ext.getCmp('tglpenjgridid').getValue()
                        }
                    },
                    scope: this
                },
                load: {
                    fn: function (a, b, c) {
                        c.params = {};
                    },
                    scope: this
                }
            }),
            jun.rztReturBotol.on({
                beforeload: {
                    fn: function (a, b) {
                        b.params = {
                            sales: Ext.getCmp('salespenjgridid').getValue(),
                            tgl: Ext.getCmp('tglpenjgridid').getValue()
                        }
                    },
                    scope: this
                }
            })
    },
    onbtnKirimClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var r = new jun.LapPengiriman();
        r.show();
        r.tgl.setValue(tgl);
        r.sales.setValue(sales);
    },
    onbtnKasMasuk: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var r = new jun.LapKasMasuk();
        r.show();
        r.tgl.setValue(tgl);
        r.sales.setValue(sales);
    },
    onbtnCetakClick: function () {
        var record = this.sm.getSelected();
        // Check is list selected
        if (record == undefined) {
            Ext.MessageBox.alert("Warning", "Anda Belum Memilih Faktur");
            return;
        }
        var r = new jun.PrintFakturJual();
        r.doc_ref.setValue(record.data.doc_ref);
        r.penjualan_id.setValue(record.data.penjualan_id);
        r.show();
    },
    onbtnSetorKasClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        if (jun.rztSetorKasSales.totalLength == 0) {
            Ext.MessageBox
                .confirm(
                'Pertanyaan',
                'Setoran Kas belum dibuat.<br>Apakah anda ingin membuat Setoran Kas sekarang?',
                function (btn) {
                    if (btn == 'no') {
                        return;
                    }
                    if (jun.rztReturBotol.totalLength == 0) {
                        Ext.MessageBox.show({
                            title: 'Error',
                            msg: "Retur Botol belum dibuat.",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });
                        return;
                    }
                    if (jun.rztDof.totalLength == 0) {
                        Ext.MessageBox.show({
                            title: 'Error',
                            msg: "DO Final belum dibuat.",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });
                        return;
                    }
                    if (jun.rztBiayaSales.totalLength == 0) {
                        Ext.MessageBox
                            .confirm(
                            'Pertanyaan',
                            'Biaya sales belum dibuat.<br>Apakah anda yakin ingin membuat Setoran Kas sekarang tanpa mengisi biaya sales?',
                            function (btn) {
                                if (btn == 'no') {
                                    return;
                                }
                            });
                    }
                    Ext.Ajax.request({
                        url: 'SetorKasSales/create',
                        method: 'POST',
                        params: {
                            sales: sales,
                            tgl: tgl
                        },
                        success: function (f, a) {
                            jun.rztSetorKasSales.reload();
                            var response = Ext
                                .decode(f.responseText);
                            Ext.MessageBox.show({
                                title: 'Info',
                                msg: response.msg,
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.INFO
                            });
                        },
                        failure: function (f, a) {
                            switch (a.failureType) {
                                case Ext.form.Action.CLIENT_INVALID:
                                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                    break;
                                case Ext.form.Action.CONNECT_FAILURE:
                                    Ext.Msg.alert(a.response.statusText, a.response.responseText);
                                    break;
                                case Ext.form.Action.SERVER_INVALID:
                                    Ext.Msg.alert('Failure', a.result.msg);
                            }
                        },
                        scope: this
                    });
                });
        } else {
            var r = new jun.ReportSetorKas();
            r.show();
            r.tgl.setValue(tgl);
            r.sales.setValue(sales);
        }
    },
    onbtnReturBotolClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var form = new jun.ReturBotolWin();
        form.tgl.setValue(tgl);
        form.sales.setValue(sales);
        if (jun.rztReturBotol.totalLength == 0) {
            if (jun.rztSetorKasSales.totalLength == 0) {
                form.modez = 0
            } else {
                form.modez = 1;
            }
            jun.rztReturBotolDetil.baseParams = {
                sales: sales,
                tgl: tgl
            };
        } else {
            form.modez = 1;
            form.formz.getForm().loadRecord(jun.rztReturBotol.data.items[0]);
            form.id = jun.rztReturBotol.data.items[0].data.retur_botol_id;
            jun.rztReturBotolDetil.baseParams = {
                sales: sales,
                tgl: tgl,
                id: jun.rztReturBotol.data.items[0].data.retur_botol_id
            };
        }
        jun.rztReturBotolDetil.reload();
        jun.rztReturBotolDetil.baseParams = {};
        form.show();
    },
    onbtnBebanSalesClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var sales = this.sales.getValue();
        var tgl = this.tgl.getValue();
        var form = new jun.BiayaSalesWin();
        if (jun.rztBiayaSales.totalLength == 0) {
            if (jun.rztSetorKasSales.totalLength == 0) {
                form.modez = 0
            } else {
                form.modez = 1;
            }
        } else {
            form.formz.getForm().loadRecord(jun.rztBiayaSales.data.items[0]);
            form.id = jun.rztBiayaSales.data.items[0].data.biaya_sales_id;
            jun.rztBiayaSalesLain.baseParams = {
                id: jun.rztBiayaSales.data.items[0].data.biaya_sales_id
            };
            jun.rztBiayaSalesLain.reload();
            jun.rztBiayaSalesLain.baseParams = {};
            form.modez = 1;
        }
        form.tgl.setValue(tgl);
        form.sales.setValue(sales);
        form.show();
    },
    onbtnPiutangClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var form = new jun.PelunasanPiutangWin();
        if (jun.rztSetorKasSales.totalLength == 0) {
            form.modez = 0
        } else {
            form.modez = 1;
        }
        form.show();
        form.tgl.setValue(tgl);
        form.sales.setValue(sales);
    },
    onbtnDOSClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        if (jun.rztDos.totalLength == 0) {
            Ext.MessageBox
                .confirm(
                'Pertanyaan',
                'DO Sementara belum dibuat.<br>Apakah anda ingin membuat DO Sementara sekarang?',
                function (btn) {
                    if (btn == 'no') {
                        return;
                    }
                    var sales = Ext.getCmp('salespenjgridid').getValue();
                    var tgl = Ext.getCmp('tglpenjgridid').getValue();
                    Ext.Ajax.request({
                        url: 'Dos/create',
                        method: 'POST',
                        params: {
                            sales: sales,
                            tgl: tgl
                        },
                        success: function (f, a) {
                            jun.rztDos.reload();
                            var response = Ext
                                .decode(f.responseText);
                            Ext.MessageBox.show({
                                title: 'Info',
                                msg: response.msg,
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.INFO
                            });
                        },
                        failure: function (f, a) {
                            var msg = 'server-side failure with status code ' + f.status;
                            if (a.failureType == 'server') {
                                msg = a.result.msg;
                            }
                            Ext.MessageBox.show({
                                title: 'Warning',
                                msg: msg,
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                        },
                        scope: this
                    });
                });
        } else {
            var r = new jun.ReportDOS();
            r.show();
            r.tgl.setValue(this.tgl.getValue());
            r.sales.setValue(this.sales.getValue());
        }
    },
    onbtnDOFClick: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var idx = jun.rztPenjualan.findExact("final", "0");
        if (idx > -1) {
            var j = jun.rztPenjualan.getAt(idx);
            Ext.MessageBox.show({
                title: 'Info',
                msg: "DO Final tidak bisa dibuat karena penjualan "
                         + j.data.doc_ref + "<br>belum final.",
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.INFO
            });
            return;
        }
        if (jun.rztDos.totalLength == 0) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: "DO Sementara belum dibuat.",
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
            return;
        }
        var sales = Ext.getCmp('salespenjgridid').getValue();
        var tgl = Ext.getCmp('tglpenjgridid').getValue();
        var form = new jun.DofWin();
        form.tgl.setValue(tgl);
        form.sales.setValue(sales);
        if (jun.rztDof.totalLength == 0) {
            if (jun.rztSetorKasSales.totalLength == 0) {
                form.modez = 0
            } else {
                form.modez = 1;
            }
            jun.rztDofDetil.baseParams = {
                sales: sales,
                tgl: tgl
            };
        } else {
            form.modez = 1;
            form.formz.getForm().loadRecord(jun.rztDof.data.items[0]);
            form.id = jun.rztDof.data.items[0].data.dof_id;
            jun.rztDofDetil.baseParams = {
                sales: sales,
                tgl: tgl,
                id: jun.rztDof.data.items[0].data.dof_id
            };
        }
        jun.rztDofDetil.reload();
        jun.rztDofDetil.baseParams = {};
        form.show();
    },
    onSalesChange: function () {
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            return;
        }
        this.store.baseParams = {
            mode: "grid",
            sales: sales,
            tgl: tgl
        };
        this.store.reload();
        this.store.baseParams = {};
        jun.rztSetorKasSales.reload();
        jun.rztReturBotol.reload();
        jun.rztDof.reload();
        jun.rztDos.reload();
        jun.rztBiayaSales.reload();
        jun.rztReturJual.reload();
    },
    getrow: function (sm, idx, r) {
        this.record = r;
        var selectedz = this.sm.getSelections();
    },
    loadForm: function () {
        if (jun.rztDof.totalLength > 0) {
            Ext.MessageBox.show({
                title: 'Error',
                msg: "Tidak bisa membuat faktur baru karena DO Final sudah dibuat.",
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.ERROR
            });
            return;
        }
        var tgl = this.tgl.getValue();
        var sales = this.sales.getValue();
        if (tgl == "" || sales == "") {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih Tanggal atau Sales");
            return;
        }
        var form = new jun.PenjualanWin({
            modez: 0
        });
        form.show();
        form.tgl.setValue(tgl);
        form.sales.setValue(sales);
        form.btnSave.setVisible(true);
        form.btnFinal.setVisible(true);
    },
    loadEditForm: function () {
        var selectedz = this.sm.getSelected();
        if (selectedz == undefined) {
            Ext.MessageBox.alert("Warning",
                "Anda belum memilih faktur");
            return;
        }
        var idz = selectedz.json.penjualan_id;
        var form = new jun.PenjualanWin({
            modez: 1,
            id: idz
        });
        form.show(this);
        form.formz.getForm().loadRecord(this.record);
        if (this.record.data.final == "1") {
            form.btnSave.setVisible(false);
            form.btnFinal.setVisible(false);
        } else {
            form.btnSave.setVisible(true);
            form.btnFinal.setVisible(true);
        }
        form.onKonsumenChange();
        jun.rztDetilPenjualan.baseParams = {
            penjualan_id: idz
        };
        jun.rztDetilPenjualan.load();
        jun.rztDetilPenjualan.baseParams = {};
    },
    deleteRec: function () {
        Ext.MessageBox.confirm('Pertanyaan',
            'Apakah anda yakin ingin menghapus data ini?',
            this.deleteRecYes, this);
    },
    deleteRecYes: function (btn) {
        if (btn == 'no') {
            return;
        }
        var record = this.sm.getSelected();
        // Check is list selected
        if (record == "") {
            Ext.MessageBox.alert("Warning", "Anda Belum Memilih Data");
            return;
        }
        Ext.Ajax.request({
            url: 'Penjualan/delete/id/' + record.json.penjualan_id,
            method: 'POST',
            success: function (f, a) {
                jun.rztPenjualan.reload();
                var response = Ext.decode(f.responseText);
                Ext.MessageBox.show({
                    title: 'Info',
                    msg: response.msg,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                });
            },
            failure: function (f, a) {
                var msg = 'server-side failure with status code ' + f.status;
                if (a.failureType == 'server') {
                    msg = a.result.msg;
                }
                Ext.MessageBox.show({
                    title: 'Warning',
                    msg: msg,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                });
            }
        });
    }
})